var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// 引入插件 - 用于处理表单数据
var mutler = require("multer")()
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var fsp = require('fs/promises')

var app = express();
var buffList=Buffer.alloc(0);
var nameList=[];

app.post("/film/upload", async function (req, res, next) {
    nameList.push(req.headers["x-file-name"])
    var result=await getData(req);
    buffList=Buffer.concat([buffList,result],buffList.length+result.length);
    res.end(JSON.stringify({errno:200,message:"接收完成"}))
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
// 处理表到数据
app.use(mutler.none())
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.post("/film/uploadfinished",async function(req,res,next){
  await fsp.writeFile(path.join(path.resolve(),"public/images/"+req.body.name+"."+req.body.extName),buffList,"base64");
  buffList=Buffer.alloc(0);
  nameList.length=0;
  res.end(JSON.stringify({
    url: 'http://localhost:4000/images/' + req.body.name + "." + req.body.extName,
    thumbUrl: 'http://localhost:4000/images/' + req.body.name + "." + req.body.extName,
    status: 'done',
    name: req.body.name + "." + req.body.extName
  }))
})
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

function getData(req) {
  return new Promise((resolve, reject) => {
    let data = Buffer.alloc(0);
    req.on("data", (_chunk) => {
      data = Buffer.concat([data, _chunk], data.length + _chunk.length)
    })
    req.on("end", () => {
      resolve(data);
    })
  })
}


module.exports = app;
